<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles" round>添加角色</el-button>
        </el-col>
      </el-row>

      <el-table width="100%" border stripe :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item, index) in scope.row.children"
              :key="index"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRightbyId(scope.row, item.id)" closable>{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级、三级权限 -->
              <el-col :span="19">
                <!-- 嵌套渲染二级权限 -->
                <el-row
                  :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, index2) in item.children"
                  :key="index2"
                >
                  <el-col :span="6">
                    <el-tag
                      @close="removeRightbyId(scope.row, item2.id)"
                      closable
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      @close="removeRightbyId(scope.row, item3.id)"
                      closable
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="index3"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="序号"
          type="index"
        ></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="showSetEditrolesdialog(scope.row)" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="removeRoles(scope.row.id)" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              @click="showSetRightdialog(scope.row)"
              size="mini"
              type="warning"
              icon="el-icon-setting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog
      @close="SetRightdialogClose"
      width="50%"
      title="分配权限"
      :visible.sync="SetRightdialogVisable"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        ref="treeRef"
        :default-checked-keys="defkes"
        :default-expand-all="true"
        node-key="id"
        show-checkbox
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightdialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog
      width="50%"
      title="添加角色"
      :visible.sync="AddRolesdialogVisable"
      @close="addRolesdialogcolse"
    >
      <el-form
        :model="addFrom"
        :rules="addFromRules"
        ref="addRef"
        
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddRolesdialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="saveRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog
      width="50%"
      title="修改角色"
      :visible.sync="EditRolesdialogVisable"
      @close="editdialogcolse"
    >
      <el-form
        :model="EditFrom"
        :rules="EditFromRules"
        ref="EditRef"
        
      >
      <el-form-item label="角色id" prop="roleId">
          <el-input v-model="EditFrom.roleId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="EditFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="EditFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditRolesdialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="EditRolesInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      SetRightdialogVisable: false,
      rightslist: [],
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      // 默认选中的节点id值
      defkes: [],
      // 当前即将分配角色权限的id
      roelID: '',
      AddRolesdialogVisable: false,
      addFrom: {
        roleName: '',
        roleDesc: '',
      },
      addFromRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        roleDesc:[
            { required: true, message: '请输入角色描述', trigger: 'blur' },
        ]
      },
      EditRolesdialogVisable:false,
      EditFrom:{
        roleId:'',
        roleName:'',
        roleDesc:'',
      },
      EditFromRules:{
          roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        roleDesc:[
            { required: true, message: '请输入角色描述', trigger: 'blur' },
        ]
      }
    }
  },
  created() {
    this.getrolesList()
  },
  methods: {
    async getrolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    async removeRightbyId(role, rightId) {
      // 弹框提示
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      role.children = res.data
    },
    async showSetRightdialog(role) {
      this.roelID = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$http.error('获取权限数据失败！')
      }
      //获取权限数据保存的数组中
      this.rightslist = res.data
      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defkes)

      this.SetRightdialogVisable = true
    },
    // 通过递归形式，获取角色下所有三级权限的id
    // 并保存到 defkes数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    SetRightdialogClose() {
      this.defkes = []
    },
    // 为角色分配权限
    async allotRights() {
      // ...是展开运输符
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]

      const idSrt = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roelID}/rights`,
        { rids: idSrt }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('角色分配失败！')
      }
      this.$message.success('角色分配成功！')
      this.getrolesList()
      this.SetRightdialogVisable = false
    },
    // 添加角色
    addRoles() {
      this.AddRolesdialogVisable = true
      
    },
    // 添加角色请求
    saveRoles(){
        this.$refs.addRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addFrom)
        if (res.meta.status !== 200) {
          this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        this.AddRolesdialogVisable = false
        this.getrolesList()
      })
    },
    addRolesdialogcolse(){
           this.$refs.addFromRules.resetFields()
    },
    showSetEditrolesdialog(row){
        this.EditRolesdialogVisable=true
        this.EditFrom.roleId=row.id
        this.EditFrom.roleName=row.roleName
        this.EditFrom.roleDesc=row.roleDesc

    },
    // 修改用户角色功能
    EditRolesInfo(){
       this.$refs.EditRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.EditFrom.roleId,
          {
            roleName: this.EditFrom.roleName,
            roleDesc: this.EditFrom.roleDesc,
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('修改角色失败！')
        }
        this.$message.success('修改角色成功！')
        this.EditRolesdialogVisable = false
        this.getrolesList()
      })
    },
    editdialogcolse(){
         this.$refs.EditRef.resetFields()
    },
    // 删除角色功能
   async removeRoles(id){
        const confirmResult = await this.$confirm(
        '此操作将删除角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return his.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getrolesList()
    }

  },
}
</script>
<style  scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 8px;
}
.bdtop {
  border-top: 1px solid lightskyblue;
}
.bdbottom {
  border-bottom: 1px solid lightskyblue;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>